<?php

class Model_Listing_Car extends Model_Listing implements Model_Listing_Interface
{
    const HORSEPOWER_MIN = 0;
    const HORSEPOWER_MAX = 350;
    const MILEAGE_MIN = 0;
    const MILEAGE_MAX = 200000;
    
    protected static  $_collection = 'listing';

    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
            'fac'  => array('Array'), //category
            'vie'  => array('Array'), //category
            'roo'  => array('Array'), //category
            'lay'  => array('Array'), //category
            'out'  => array('Array'), //category
            'con'  => array('Array'), //category
            'exc'  => array('Array'), //exteriorcolor
            'ecf'  => array('Array'), //exteriorcolor
            'inc'  => array('Array'), //exteriorcolor
            'saf'  => array('Array'), //exteriorcolor
            'po'  => array('Array'), //exteriorcolor
        );

    protected $_category = array();

    public function __construct($data = array(), $config = array()) {
        static::$_transcript = array_merge(array(
            'ma'   => 'make',
            'mo'   => 'model',
            'ym'   => 'yearmanufactured',
            'cty'  => 'cartype',
            'npo'  => 'numberpreviousowner',
            'inc'  => 'interiorcolor',
            'saf'  => 'safetyfeatures',
            'po'   => 'poweroptions',
            'exc'  => 'exteriorcolor',
            'do'   => 'doors',
            'ecf'  => 'entertainmentfeatures',
            'dit'  => 'drivetype',
            'mil'  => 'mileage',
            'eng'  => 'engine',
            'hp'   => 'horsepower',
            'tr'   => 'transmission',
            'fue'  => 'fueleconomy',
            'fu'   => 'fuel',
            'sb'   => 'saleby',
            'arl1'   => 'area_l1',
            'arl2'   => 'area_l2',
            'cap'  => 'capacity',
            'dsp'  => 'displacement',
            'brs'  => 'brandsale',
        ), static::$_transcript);
        parent::__construct($data, $config);
    }
	
	public static function getTranslationFormField()
    {
        $arr = array(
			'tl_en' =>'text',
			'cs_en' =>'textarea',
		);
		
		return $arr;
    }
	
    public function postAnAddForm($options = array()) {
        $options = array_merge($options, array('category' => $this->category));
        return new Listing_Form_PostAnAddCarForm($options);
    }

    public function getAdDetailPartialName()
    {
        return 'customization/car.phtml';
    }

    public function getAdPreviewPartialName()
    {
        return $this->getAdDetailPartialName();
    }


    public static function getSearchResultPartialName()
    {
        return 'cars';
    }

    public static function getRefineSearchForm()
    {
        return new Search_Form_CarRefineForm();
    }

    public function __get($name)
    {
        if ($name == 'model') {
            return  Model_Listing_Attribute::one(array('_id' => new MongoId($this->mo)));
        } elseif ($name == 'make') {
            return  Model_Listing_Attribute::one(array('_id' => new MongoId($this->ma)));
        } else {
            return parent::__get($name);
        }
    }
    
    public static function getSearchTextTerms() 
    {
        return array(
            'description' => '1.0', 
            'title' => '7.0', 
            'make_name' => '9.0', 
            'model_name' => '9.0',
            'area_l2_name' => '9.0',
            'street' => '7.0',
            'cartype_name' => '7.0',
            'interiorcolor_name' => '5.0',
            'exteriorcolor_name' => '5.0',
            'safetyfeatures_name' => '5.0',
            'poweroptions_name' => '5.0',
            'entertainmentfeatures_name' => '5.0',
            'drivetype_name' => '5.0',
            'fuel_name' => '5.0',
        );
    }
    
    
    /*
     * return a list of all the possible values that should be extracted from the keyword search and be specified as exact term
     * 
     */
    public static function getExactSeachTerms() 
    {
       return array(
                'cartype_name'              => self::getCarType(),
                'interiorcolor_name'         => self::getIntColor(),
                'exteriorcolor_name'         => self::getExtColor(),
                'safetyfeatures_name'        => self::getSafetyFeatures(),
                'poweroptions_name'          => self::getPowerOptions(),
                'entertainmentfeatures_name' => self::getEntertComm(),
                'drivetype_name'             => self::getDriveType(),
                'fuel_name'                  => self::getFuel(),
                'yearmanufactured'           => self::getYearManufactured(),
           );
    }        
    
    public static function processRefineSearchForm(&$get, $page, $per_page, &$query, &$fields, &$additionalParameters)
    {
        //echo '<pre>';print_r($_GET);exit;

        //$q       = isset($_GET['keyword']) ? strtolower($_GET['keyword']) : false;
        $results = false;
        if (empty($fields)) {
            $fields  = array('description', 'title', 'area_l2_name', 'area_l1_name', 'street');
        }
        $values  = array();
        if(empty($additionalParameters)) {
            $additionalParameters = array();
        }
       // $get     = $_GET;
/*
        if (!empty($get['keyword_car'])) {
            $values['description'] = ' '.strtolower($get['keyword_car']).' ';
            $values['title']       = ' '.strtolower($get['keyword_car']).' ';
            $values['make']       = ' '.strtolower($get['keyword_car']).' ';
            $values['model']       = ' '.strtolower($get['keyword_car']).' ';
            $values['district']       = ' '.strtolower($get['keyword_car']).' ';
            $values['street']       = ' '.strtolower($get['keyword_car']).' ';
            $values['cartype']       = ' '.strtolower($get['keyword_car']).' ';
            
            //$bf = 'model^9.0 model^9.0 district^9.0 title^7.0 street^7.0 cartype^7.0';
        }


        

       // echo '<pre>';print_r($values);
        foreach($values as $k => $val) {
            if (is_array($val)) {
                $tmp = array();
                foreach($val as $k2 => $v2) {
                    $tmp[] = ' '.$k.':'.$v2;
                }
                $values[$k] = '('.implode(' OR ', $tmp).')';
            } else {
                $values[$k] = ' '.$k.':'.$val;
            }
        }

        if (!empty($values)) {
            $query = implode(' ', $values);
        } else {
            $query = '*:*';
        }
*/
        $search_terms = self::getSearchTextTerms();
        
        $exact_search_terms = self::getExactSeachTerms();
        
        $q      = '';
        $qq     = $get['keyword'];
        $to_add = ' ';

        //add the username
        if (!empty($get['keyword'])) {
            //$q = '(username_lower:"'.$get['keyword'].'"^50.0) ';
        }

        if (!empty($exact_search_terms)) {
            foreach($exact_search_terms as $name => $val) {
                foreach($val as $k => $v) {
                    if (trim(strtolower($v)) != 'all' && preg_match('#('.trim($v).')#i', $get['keyword'], $match)) {
                        //var_dump($match, $v, $get['keyword'], str_ireplace( $v, '', $get['keyword']));exit;
                        $get['keyword'] = str_ireplace( $v, '', $get['keyword']);
                        $q .= $to_add.str_replace('_name', '', $name) .':'.$k.'^5.0 ';
                        $to_add = ' OR ';
                    }
                }
            }
            if (!empty($q) && !empty($tmp)) {
                $q = ' OR ('.$tmp.') ';
            }
        }
        
        $to_add = ' ';
        
        //remove quoted words and add them to q
        $bak = $get['keyword'];
        
        
        $arr = preg_match_all('#\"(.*?)\"#i', $get['keyword'], $match);
        foreach ($match[1] as $v) {
            $q .= ' AND "'.$v.'"';
        }
        $get['keyword'] = preg_replace('#"(.*?)"#i', '', $get['keyword']);
        $qf = '';
        foreach($search_terms as $v => $weight) {
            $qf .= $v.'^'.$weight.' ';
        }
        
        if (!empty($qf)) {
            $additionalParameters['qf'] = $qf;
        }
        if (!empty($qq)) {
            $additionalParameters['qq']   = $qq;
        }  
        
        $get['keyword'] = trim($get['keyword']);
        if (!empty($get['keyword'])) {
            if (!empty($q)) {
                $q.=' OR ';
            }
            $q .='(';
            foreach ($fields as $f) {
                $list = explode(' ', trim($get['keyword']));
                foreach($list as $vl) {
                    if (!empty($vl)) {
                        $q .= $to_add.''.$f.':'.$vl;
                        $to_add = ' OR ';
                    }
                }
            }
            $q.=') ';
        }
        
        
        $q.= ' OR _query_:"{!dismax qf=$qf v=$qq}" ';
        
        if (empty($_GET['keyword'])) {
            $q = '*:*';
        }
        
        $query = $q;
        $get['sort'] = empty($get['sort']) ? '' : $get['sort'];
        
        switch ($get['sort']) {
            case 'highest':
                $get['sort'] = 'highest';
                $sort = 'price desc';
                break;
            case 'lowest':
                $get['sort'] = 'lowest';
                $sort = 'is_free asc, price asc';
                break;
            case 'rel':
                $get['sort'] = 'rel';
                $sort = 'score desc';
                break;
            case 'recent':
                $get['sort'] = 'recent';
                $sort = 'posted_at desc';
                break;
            case 'status':
                $get['sort'] = 'status';
                $sort = 'status desc';
                break;
            default:
                if (!empty($get['keyword_car'])) {
                    $get['sort'] = 'rel';
                    $sort         = 'score desc';
                } else {
                    $get['sort'] = 'recent';
                    $sort         = 'posted_at desc';
                }
        }

        $additionalParameters['fl']   = '*,score';
        $additionalParameters['sort'] = $sort;

        //boost
       // $additionalParameters['bf'] = 'make^9.0 model^9.0 district^9.0 title^7.0 street^7.0 cartype^7.0';


        //Parameters to refine search
        $fq         = '';
        $valuesplus = array();

        //Has Image
        if (!empty($get['has_image'])) {
            $valuesplus['has_image'] = true;
        }
        //Preferred Seller
        if (!empty($get['agency_owner_car'])) {
            $valuesplus['saleby'] = $get['agency_owner_car'];
        }
        elseif (!empty($get['seller']['saleby'])) {
            $valuesplus['saleby'] = $get['seller']['saleby'];
        }

        // Sale by
        if (!empty($get['wantto_car'])) {
            $buy_rent = $get['wantto_car'];
        }
        elseif (!empty($get['want_to']['buy_rent'])) {
            $buy_rent = $get['want_to']['buy_rent'];
        }

        // Sale by
        if (!empty($buy_rent)) {
            if ($buy_rent == 'Buy') {
                //Sale Category
                $sales = array();
                $sale = Model_Category::one(array('id' => 'c458'));
                $sales1 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c464'));
                $sales2 = $sale->_id;
                $category = ' +(category:'.$sales1.' OR category:'.$sales2.') ';
            }
            elseif ($buy_rent == 'Rent') {
                $rents = array();
                $rent = Model_Category::one(array('id' => 'c463'));
                $rents1 = $rent->_id;
                $category = ' +category:'.$rents1.' ';
            }
            else {
                $category = ' ';
            }
        }

        //Force only Cars
        //$valuesplus['type_obj_s'] = 'Model_Listing_Car';
        $valuesplus['type_obj_s'] = 'Model_Listing';

        //Make
        if (!empty($get['make'])) {
            $valuesplus['make'] = $get['make'];
        }

        //Model
        if (!empty($get['model'])) {
            $valuesplus['model'] = $get['model'];
        }

        //Price
        if (isset($get['price_car']) && isset($get['price_car-1'])) {
            $price  = $get['price_car'];
            $price1 = $get['price_car-1'];
        }
        if (isset($price) && isset($price1)) {
            $test1 = false;$test2 = false;
            if (empty($price1)) {
                $price1 = '*';
                $test1  = true;
            }
            if (empty($price)) {
                $price = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['price'] = '['.intval(str_replace(",","",$price)).' TO '.intval(str_replace(",","",$price1)).']';
            }
        }

        //Car Type
        
        if (!empty($get['cartype'])) {
            $valuesplus['cartype'] = $get['cartype'];
        }

        //Capacity
        if (!empty($get['capacity'])) {
            $valuesplus['capacity'] = $get['capacity'];
        }

        //Year Manufactured
        if (!empty($get['yearmanufactured'])) {
            $valuesplus['yearmanufactured'] = $get['yearmanufactured'];
        }
        if (!empty($get['yearmanufactured_car'])) {
            $valuesplus['yearmanufactured'] = $get['yearmanufactured_car'];
        }

        //No of previous Owners
        if (!empty($get['previousowners'])) {
            $valuesplus['nopreviousowners'] = $get['previousowners'];
        }

        //Doors
        if (!empty($get['optional']['doors'])) {
            $valuesplus['doors'] = $get['optional']['doors'];
        }

        //Entertainment
        if (!empty($get['optional']['entertcomm'])) {
            $valuesplus['entertainmentfeatures'] = $get['optional']['entertcomm'];
        }

        //Exterior Color
        if (!empty($get['optional']['extcolor'])) {
            $valuesplus['exteriorcolor'] = $get['optional']['extcolor'];
        }

        //Interior Color
        if (!empty($get['optional']['intcolor'])) {
            $valuesplus['interiorcolor'] = $get['optional']['intcolor'];
        }

        //Power Options
        if (!empty($get['optional']['poweroptions'])) {
            $valuesplus['poweroptions'] = $get['optional']['poweroptions'];
        }

        //Safety Features
        if (!empty($get['optional']['safetyfeatures'])) {
            $valuesplus['safetyfeatures'] = $get['optional']['safetyfeatures'];
        }
        
        //Mileage
        if (isset($get['optional-mileage']) && isset($get['optional-mileage-1'])) {
            $test1 = false;$test2 = false;
            if ($get['optional-mileage-1'] == Model_Listing_Car::MILEAGE_MAX) {
                $get['optional-mileage-1'] = '*';
                $test1 = true;
            }
            if ($get['optional-mileage'] == Model_Listing_Car::MILEAGE_MIN) {
                $get['optional-mileage'] = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['mileage'] = '['.$get['optional-mileage'].' TO '.$get['optional-mileage-1'].']';
            }
        }

        //Horsepower
        if (isset($get['optional-horsepower']) && isset($get['optional-horsepower-1'])) {
            $test1 = false;$test2 = false;
            if ($get['optional-horsepower-1'] == Model_Listing_Car::HORSEPOWER_MAX) {
                $get['optional-horsepower-1'] = '*';
                $test1 = true;
            }
            if ($get['optional-horsepower'] == Model_Listing_Car::HORSEPOWER_MIN) {
                $get['optional-horsepower'] = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['horsepower'] = '['.$get['optional-horsepower'].' TO '.$get['optional-horsepower-1'].']';
            }
        }

        //Engine
        if (!empty($_GET['optional']['engine'])) {
            $valuesplus['engine'] = $_GET['optional']['engine'];
        }

        //Transmission
        if (!empty($_GET['optional']['transmission'])) {
            $valuesplus['transmission'] = $_GET['optional']['transmission'];
        }

        //Fuel Economy
        if (!empty($_GET['optional']['fueleconomy'])) {
            $valuesplus['fueleconomy'] = $_GET['optional']['fueleconomy'];
        }
        
        //Fuel
        if (!empty($_GET['optional']['fuel'])) {
            $valuesplus['fuel'] = $_GET['optional']['fuel'];
        }
        
        // District
        if (!empty($get['area_l2'])) {
            $valuesplus['area_l2'] = $get['area_l2'];
        }
        elseif (!empty($get['performances']['area_l2'])) {
            $valuesplus['area_l2'] = $get['performances']['area_l2'];
        }

        if (!empty($get['city'])) {
            $valuesplus['city'] = (int) $_GET['city'];
        }

        foreach($valuesplus as $k => $val) {
          $valuesplus[$k] = '+'.$k.':'.$val.' ';
        }

        if (!empty($category)) {
            $fq .= $category;
        }

        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }

        //Drive Type
        if ((!empty($get['optional']['AWD'])) || (!empty($get['optional']['2WD'])) || (!empty($get['optional']['4WD']))){
            if (!empty($get['optional']['2WD'])) {
                $value1 = 1;
            } else {$value1 = 0;}
            if (!empty($get['optional']['4WD'])) {
                $value2 = 2;
            } else {$value2 = 0;}
            if (!empty($get['optional']['AWD'])) {
                $value3 = 3;
            } else {$value3 = 0;}
            if (($value1 == 0) && ($value2 == 0)) {
                $additionalParameters['fq'] = $additionalParameters['fq'].' +drivetype:'.$value3.' ';
            }
            elseif (($value1 == 0) && ($value3 == 0)) {
                $additionalParameters['fq'] = $additionalParameters['fq'].' +drivetype:'.$value2.' ';
            }
            elseif (($value2 == 0) && ($value3 == 0)) {
                $additionalParameters['fq'] = $additionalParameters['fq'].' +drivetype:'.$value1.' ';
            }
            else {
                if ($value1 == 0) {
                    $additionalParameters['fq'] = $additionalParameters['fq'].' +(drivetype:'.$value2.' OR drivetype:'.$value3.') ';
                }
                elseif ($value2 == 0) {
                    $additionalParameters['fq'] = $additionalParameters['fq'].' +(drivetype:'.$value1.' OR drivetype:'.$value3.') ';
                }
                elseif ($value3 == 0) {
                    $additionalParameters['fq'] = $additionalParameters['fq'].' +(drivetype:'.$value1.' OR drivetype:'.$value2.') ';
                }
                else {
                    $additionalParameters['fq'] = $additionalParameters['fq'].' +(drivetype:'.$value1.' OR drivetype:'.$value2.' OR drivetype:'.$value3.') ';
                }                
            }
        }

        //echo '<PRE>';
        //print_r($additionalParameters);
        //exit;
    }

    public static function getMake()
    {
        $make = array();
        $attr      = Model_Listing_Attribute::all(array('type' => 'cars', 'path' => array('$exists' => 0)))->sort(array('or' => 1, 'nm_en' => 1));
        $make[''] = 'All';

        foreach($attr as $k => $loc) {
            $make[(string) $loc->_id] = $loc->name;
        }

        return $make;        
    }
	
	public static function getMake2($name)
    {
		$name = strtoupper($name);
        $key = 'nm_' . Zend_Registry::get('current_language');
        $attr      = Model_Listing_Attribute::one(array('type' => 'cars', $key => $name, 'path' => array('$exists' => 0)));
        if (!empty($attr)) {
            return $attr->_id;
        }

        return null;        
    }

    /* find a make and model when both are attached */
    public static function findMakeModel($name)
    {
        $key = 'nm_' . Zend_Registry::get('current_language');
        $res = array('make' => null, 'model' => null);
        for ($count = 2; $count <= mb_strlen($name); $count++) {
            $value = mb_substr($name, 0, $count);
            echo "test: $value\n";
            $attr      = Model_Listing_Attribute::one(array('type' => 'cars', $key => $value, 'path' => array('$exists' => false)));
            if (!empty($attr)) {
                $res['make'] = $attr->_id;
                
                $model = mb_substr($name, $count);
                $attr      = Model_Listing_Attribute::one(array('type' => 'cars', $key => $model, 'path' => array('$size' => 2)));
                if (!empty($attr)) {
                    $res['model'] = $attr->_id;
                    
                }
                return $res;
            }
        }
    }

    public static function getMakePostAd()
    {
        $make = array();
        $attr      = Model_Listing_Attribute::all(array('type' => 'cars', 'path' => array('$exists' => 0), 'cn' => array('$exists' => true)))->sort(array('or' => 1, 'py' => 1));
        $make[''] = 'Select';

        foreach($attr as $k => $loc) {
            $make[(string) $loc->_id] = $loc->nm_sc;
        }

        return $make;
    }

    public static function getModel($id)
    {
        $model = array();
        $attr = Model_Listing_Attribute::all(array('path' => new MongoId($id)))->sort(array('or' => 1, 'nm_en' => 1));
        $model[''] = 'All';
        
        foreach($attr as $k => $loc) {
            if ($loc->name == 'All') {
                $model[''] = $loc->name;
            }
            else {
                $model[(string) $loc->_id] = $loc->name;
            }
        }

        return $model;
    }

    public static function getModelPostAd($id)
    {
        $model = array();
        $attr = Model_Listing_Attribute::all(array('path' => new MongoId($id), 'nm_sc' => array('$exists' => true)))->sort(array('or' => 1, 'py' => 1));
        $model[''] = 'Select';

        foreach($attr as $k => $loc) {
            $model[(string) $loc->_id] = $loc->nm_sc;
        }

        return $model;
    }

    public static function getYearManufactured($id = null)
    {
        $res = array('' => 'All') + self::getYearManufacturedPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;   
    }

    public static function getYearManufacturedPostAd()
    {
        return array(
            '' => 'Select',
            2011 => 2011,
            2010 => 2010,
            2009 => 2009,
            2008 => 2008,
            2007 => 2007,
            2006 => 2006,
            2005 => 2005,
            2004 => 2004,
            2003 => 2003,
            2002 => 2002,
            2001 => 2001,
            2000 => 2000,
            1999 => 1999,
            1998 => 1998,
            1997 => 1997,
            1997 => 1996,
            1997 => 1997,
            1996 => 1996,
            1995 => 1995,
            1994 => 1994,
            1993 => 1993,
            1992 => 1992,
            1991 => 1991,
            1990 => 1990,
            1989 => 1989,
            1988 => 1988,
            1987 => 1987,
            1986 => 1986,
            1985 => 1985,
            1984 => 1984,
            1983 => 1983,
            1982 => 1982,
            1981 => 1981,
            1980 => 1980,
            1979 => 1979,
            1978 => 1978,
            1977 => 1977,
            1976 => 1976,
            1975 => 1975,
            1974 => 1974,
            1973 => 1973,
            1972 => 1972,
            1971 => 1971,
            1970 => 1970,
        );
    }

    /**
     * Return the type of car
     * 
     * @param type $id specifyu the id to get the proper value
     * @return mixed (string|array) 
     */
    public static function getCarType($id = null)
    {
        $res = array('' => 'All') + self::getCarTypePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;          
    }

    public static function getCarTypePostAd()
    {
        return array(
            '' => 'Select',
            1 => '轿车',
            2 => '越野车/SUV',
            3 => 'MPV',
            4 => '跑车',
            5 => '货车/客车',
            6 => '面包车',
            7 => '皮卡',
        );
    }

    public static function getEntertComm($id = null)
    {
        $res = array('' => 'All') + self::getEntertCommPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;         
    }

    public static function getEntertCommPostAd()
    {
        
        return array(
            1 => 'CD Player',
            2 => 'DVD Player',
            3 => 'Internet Access',
            4 => 'Leather',
            5 => 'GPS, Navigation',
            6 => 'Sunroof'
        );
    }

    public static function getExtColor($id = null)
    {
        $res = array('' => 'All') + self::getColorPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getIntColor($id = null)
    {
        $res = array('' => 'All') + self::getColorPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getColorPostAd()
    {
        return array(
        	''=> 'Select',
            1 => '黑色',
            2 => '白色',
            3 => '红色',
            4 => '蓝色',
            5 => '绿色',
            6 => '黄色',
            7 => '橘色',
            8 => '香槟色',
            9 => '多颜色',
            10 => '咖啡色',
            11 => '银灰色',
            12 => '深灰色',
            13 => '金色',
            14 => '紫色',
            15 => '棕色',
            16 => '其他'
        );
    }

    public static function getEngine($id = null)
    {
        $res = array('' => 'All') + self::getEnginePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getEnginePostAd()
    {
        return array(
            1 => '4 cylinders',
            2 => '5 cylinders',
            3 => '6 cylinders',
            4 => '8 cylinders',
            5 => '10 cylinders',
            6 => '12 cylinders',
            7 => '16 cylinders'
        );
    }

    public static function getCapacity($id = null)
    {
        return array(
            '' => 'All',
            '[0 TO 600]' => '600cc or below',
            '[601 TO 1500]' => '601- 1500cc',
            '[1501 TO 2000]' => '1501 - 2000cc',
            '[2001 TO 2500]' => '2001 - 2500cc',
            '[2501 TO 3500]' => '2501- 3500cc',
            '[3501 TO 4500]' => '3501 - 4500cc',
            '[4500 TO *]' => '4500 or above'
        );
    }
    
    public static function getFuelEconomy($id = null)
    {
        $res = array('' => 'All') + self::getFuelEconomyPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }


    public static function getFuelEconomyPostAd()
    {
        return array(
            1 => 'Up to 6.4 kml',
            2 => '6.4 to 10.6 kml',
            3 => '10.6 to 14.8 kml',
            4 => '14.8 to 19.2 kml',
            5 => '19.2 kml +'
        );
    }

    public static function getFuel($id = null)
    {
        $res = array('' => 'All') + self::getFuelPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;     
    }

    public static function getFuelPostAd()
    {
        return array(
            1 => 'Bio-Diesel',
            2 => 'CNG',
            3 => 'Diesel',
            4 => 'Electric',
            5 => 'Ethanol-FFV',
            6 => 'Gasoline',
            7 => 'Hybrid-Electric',
            8 => 'Other'
        );
    }

    public static function getPreviousOwners($id = null)
    {
        $res = array('' => 'All') + self::getPreviousOwnersPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;     
    }

    public static function getPreviousOwnersPostAd()
    {
        return array(
            '' => 'Select',
            0 => '0',
            1 => '1',
            2 => '2',
            3 => '3',
            4 => '4+',
        );
    }

    public static function getDoors($id = null)
    {
        $res = array('' => 'All') + self::getDoorsPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getDoorsPostAd()
    {
        return array(
            1 => 'Two',
            2 => 'Three',
            3 => 'Four',
            4 => 'Five'
        );
    }

    public static function getPowerOptions($id = null)
    {
        $res = array('' => 'All') + self::getPowerOptionsPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res; 
    }

    public static function getPowerOptionsPostAd()
    {
        return array(
            1 => 'Air Conditioning',
            2 => 'Cruise Control',
            3 => 'Power Locks',
            4 => 'Power Mirrors',
            5 => 'Power Seats',
            6 => 'Power Windows'
        );
    }

    public static function getSafetyFeatures($id = null)
    {
        $res = array('' => 'All') + self::getSafetyFeaturesPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;        
    }

    public static function getSafetyFeaturesPostAd()
    {
        return array(
            1 => 'Anti-lock brakes (ABS)',
            2 => 'Anti-theft alarm system',
            3 => 'Driver Airbag',
            4 => 'Passenger Airbag',
            5 => 'Side Airbag',
            6 => 'Vehicle stability control (VSC)',
            7 => 'Traction Control System (TRC)',
            8 => 'Electronic Brake Distribution (EBD)',
            9 => 'Xenon Light'
        );
    }

    public static function getTransmission($id = null)
    {
        $res = array('' => 'All') + self::getTransmissionPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getTransmissionPostAd()
    {
        return array(
        	''=> 'Select',
            1 => '手动',
            2 => '自动',
            3 => '手自一体'
        );
    }

    public static function getDriveType($id = null)
    {
        $res = array('' => 'All') + self::getDriveTypePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getDriveTypePostAd()
    {
        return array(
            1 => '2WD',
            2 => '4WD',
            3 => 'AWD',
        );
    }

    public static function getMileagePostAd($id = null)
    {
        return array(
            1 => '5000',
            2 => '10000',
            3 => '20000',
            4 => '30000',
            5 => '40000',
            6 => '50000',
            7 => '60000',
            8 => '70000',
            9 => '80000',
            10 => '90000',
            11 => '100000',
            12 => '110000',
            13 => '120000',
            14 => '130000',
            15 => '140000',
            16 => '150000',
            17 => '160000',
            18 => '170000',
            19 => '180000',
            20 => '190000',
            21 => '200000 +'
        );
    }   

    public function getSolrDocument($document = null)
    {
        if (!$document instanceof Apache_Solr_Document) {
            $document = new Apache_Solr_Document();
        }
        $view = Zend_Registry::get('Zend_View');
        
        if(!empty($this->ma) && !empty($this->make)) {
            $document->make          = (string)$this->ma;
            $document->make_name     = (string)$this->make->name;
        }
        $document->model         = (string)$this->mo;
        if(!empty($this->mo) && !empty($this->model)) {
            $document->model_name            = (string)$this->model->name;
            if (!empty($this->model->tags) && is_array($this->model->tags)) {
                foreach($this->model->tags as $tags) {
                    $document->addField('model_name', (string)$tags);
                }
            }
        }
        if (!empty($this->ym)) {
            $document->yearmanufactured = (int)$this->ym;
        }
        if ($this->npo === 0 || !empty($this->npo)) {
            //$document->nopreviousowners = (int)$this->npo;
        }
        if (!empty($this->et)) {
            $document->enginetype       = (int)$this->et;
        }
        if (!empty($this->dit)) {
            $document->drivetype        = (string)$this->dit;
            $document->addField('drivetype_name', self::getDriveType($this->dit));
            $document->addField('drivetype_name', $view->t(self::getDriveType($this->dit), Model_Translate::TC));
        }
        if (!empty($this->sb)) {
            $document->saleby           = (string)$this->sb;
        }
        if (!empty($this->dn)) {
            $document->dealername       = (string)$this->dn;
        }
        //$document->dealerphone      = (int)$this->dp;
        //$document->dealeremail      = (string)$this->de;
        if (!empty($this->mil)) {
            //$document->mileage  = (int)$this->mil;
        }
        if (!empty($this->do)) {
            $document->doors  = (int)$this->do;
        }
        if (!empty($this->ecf)) {
            foreach ((array)$this->ecf as $data) {
                $document->addField('entertainmentfeatures', (string)$data);
                $document->addField('entertainmentfeatures_name', self::getEntertComm($data));
                $document->addField('entertainmentfeatures_name',  $view->t(self::getEntertComm($data), Model_Translate::TC));
            }        
        }
        //Cars
        if (!empty($this->eng)) {
            $document->engine           = (string)$this->eng;
        }
        if (!empty($this->cap)) {
            $document->capacity         = (int)$this->cap;
        }
        
        if (!empty($this->cty)) { 
            $document->cartype          = $this->cty;
            $document->addField('cartype_name', self::getCarType($this->cty));
            $document->addField('cartype_name', $view->t(self::getCarType($this->cty), Model_Translate::TC));
        }   
        
        if (!empty($this->hp)) {
            $document->horsepower       = (int)$this->hp;
        }
        if (!empty($this->fue)) {
            $document->fueleconomy      = (string)$this->fue;
        }
        if (!empty($this->fu)) {
            $document->fuel             = (string)$this->fu;
        }
        if (!empty($this->tr)) {
            $document->transmission_id  = (string)$this->tr;
        }

        if (!empty($this->inc)) {
            foreach ((array)$this->inc as $data) {
                $document->addField('interiorcolor', (string)$data);
                $document->addField('interiorcolor_name', self::getIntColor($data));
                $document->addField('interiorcolor_name', $view->t(self::getIntColor($data), Model_Translate::TC));
            }
        }
        if (!empty($this->exc)) {
            foreach ((array)$this->exc as $data) {
                $document->addField('exteriorcolor', (string)$data);
                $document->addField('exteriorcolor_name', self::getExtColor($data));
                $document->addField('exteriorcolor_name', $view->t(self::getExtColor($data), Model_Translate::TC));
            }
        }
        
        if (!empty($this->saf)) {
            foreach ((array)$this->saf as $data) {
                $document->addField('safetyfeatures', (string)$data);
                $document->addField('safetyfeatures_name', self::getSafetyFeatures($data));
                $document->addField('safetyfeatures_name',  $view->t(self::getSafetyFeatures($data), Model_Translate::TC));
            }
        }
        if (!empty($this->po)) {
            foreach ((array)$this->po as $data) {
                $document->addField('poweroptions', (string)$data);
                $document->addField('poweroptions_name', self::getPowerOptions($data));
                $document->addField('poweroptions_name',  $view->t(self::getPowerOptions($data), Model_Translate::TC));
            }        
        }
        return parent::getSolrDocument($document);        
    }
  
    public function getKeyword()
    {
        /*
            'ma' => 'make',
            'mo' => 'model',
            'ym' => 'yearmanufactured',
            'cty' => 'cartype',
            'npo' => 'numberpreviousowner',
            'inc' => 'interiorcolor',
            'saf' => 'safetyfeatures',
            'po' => 'poweroptions',
            'exc' => 'exteriorcolor',
            'do' => 'doors',
            'ecf' => 'entertainmentfeatures',
            'dit' => 'drivetype',
            'mil' => 'mileage',
            'eng' => 'engine',
            'hp' => 'horsepower',
            'tr' => 'transmission',
            'fue' => 'fueleconomy',
            'fu' => 'fuel',
            'sb' => 'saleby',
            'ar'  => 'area',
            'di'  => 'district',
            'cap'  => 'capacity',        
                    */
        $arr = array();
        if(!empty($this->make)) {$arr[] = $this->make->name;}
        if(!empty($this->model)) {$arr[] = $this->model->name;}
        //if(!empty($this->cartype)) {$arr[] = self::getCarType($this->cartype);}
        //if(!empty($this->exteriorcolor)) {$arr[] = self::getExtColor($this->exteriorcolor);}
        //if(!empty($this->entertainmentfeatures)) {$arr[] = self::getEntertComm($this->entertainmentfeatures);}
        //if(!empty($this->fuel)) {$arr[] = self::getFuel($this->fuel);}
        //if(!empty($this->yearmanufactured)) {$arr[] = $this->yearmanufactured;}
                
        return $arr + parent::getKeyword();
    }        
    
        /*
    public static function getFacetedSearch(&$additionalParameters)
    {
        $additionalParameters['facet'] = 'true';
        $additionalParameters['facet.field'] = 'make';
        $additionalParameters['f.make.facet.mincount'] = '1';        
    }
         *
         */

    public function exportRest($compressed = false)
    {
        $res = parent::exportRest($compressed);
        $view = Zend_Registry::get('Zend_View');


        $res['type'] = 'car';

        if ($compressed) {
            return $res;
        }
        
        /*
        if(!empty($this->make)) {
            $res['make'] = (string) $this->make->name;
            if(!empty($this->model)) {
                $res['model'] = (string) $this->model->name;
            }
        }
        $res['nbprevious'] = (string)$this->numberpreviousowner;
        $res['capacity'] = (string)$this->capacity;
        $res['year'] = (string)$this->yearmanufactured;
        if (!empty($this->cartype)) {
            $types = Model_Listing_Car::getCarType();
            $res['cartype'] = (string)$this->cartype;
            $res['cartype_en'] = (string)self::getCarType($this->cartype);
            $res['cartype_tc'] = (string)$view->t(self::getCarType($this->cartype), Model_Translate::TC);
        }
        *
         */

        if(!empty($this->make)) {
            $res['make']          = (string)$this->ma;
            $res['make_name']     = (string)$this->make->name;
        }
        if(!empty($this->model)) {
            $res['model'] = (string)$this->mo;
            $res['model_name'] = (string)$this->model->name;
            if (!empty($this->model->tags) && is_array($this->model->tags)) {
                foreach($this->model->tags as $tags) {
                    $res['model_name'] = (string)$tags;
                }
            }
        }
        if (!empty($this->ym)) {
            $res['year'] = (string)$this->ym;
        }
        if ($this->npo === 0 || !empty($this->npo)) {
            $res['noprevious'] = (string)$this->npo;
        }
        if (!empty($this->et)) {
            $res['enginetype']       = (string)$this->et;
        }
        if (!empty($this->dit)) {
            $res['drivetype']      = (string)$this->dit;
            $res['drivetype_en'] = self::getDriveType($this->dit);
            $res['drivetype_tc'] = $view->t(self::getDriveType($this->dit), Model_Translate::TC);
        }
        if (!empty($this->sb)) {
            $res['saleby']           = (string)$this->sb;
        }
        if (!empty($this->dn)) {
            $res['dealername']       = (string)$this->dn;
        }

        if (!empty($this->mil)) {
            $res['mileage']  = (string)$this->mil;
        }
        if (!empty($this->do)) {
            $res['doors']  = (string)$this->do;
        }
        if (!empty($this->ecf)) {
            foreach ((array)$this->ecf as $data) {
                $res['entertainmentfeatures'] = (string)$data;
                $res['entertainmentfeatures_en'] = self::getEntertComm($data);
                $res['entertainmentfeatures_tc'] =  $view->t(self::getEntertComm($data), Model_Translate::TC);
            }        
        }
        //Cars
        if (!empty($this->eng)) {
            $res['engine'] = (string)$this->eng;
        }
        if (!empty($this->cap)) {
            $res['capacity'] = (string)$this->cap;
        }
        
        if (!empty($this->cty)) { 
            $res['cartype'] = (string) $this->cty;
            $res['cartype_en'] = self::getCarType($this->cty);
            $res['cartype_tc'] = $view->t(self::getCarType($this->cty), Model_Translate::TC);
        }   
        
        if (!empty($this->hp)) {
            $res['horsepower'] = (string)$this->hp;
        }
        if (!empty($this->fue)) {
            $res['fueleconomy'] = (string)$this->fue;
        }
        if (!empty($this->fu)) {
            $res['fuel'] = (string)$this->fu;
        }
        if (!empty($this->tr)) {
            $res['transmission_id'] = (string)$this->tr;
        }

        if (!empty($this->inc)) {
            foreach ((array)$this->inc as $data) {
                $res['interiorcolor'] = (string)$data;
                $res['interiorcolor_en'] = self::getIntColor($data);
                $res['interiorcolor_tc'] = $view->t(self::getIntColor($data), Model_Translate::TC);
            }
        }
        if (!empty($this->exc)) {
            foreach ((array)$this->exc as $data) {
                $res['exteriorcolor'] = (string)$data;
                $res['exteriorcolor_en'] = self::getExtColor($data);
                $res['exteriorcolor_tc'] = $view->t(self::getExtColor($data), Model_Translate::TC);
            }
        }
        
        if (!empty($this->saf)) {
            foreach ((array)$this->saf as $data) {
                $res['safetyfeatures'] = (string)$data;
                $res['safetyfeatures_en'] = self::getSafetyFeatures($data);
                $res['safetyfeatures_tc'] =  $view->t(self::getSafetyFeatures($data), Model_Translate::TC);
            }
        }
        if (!empty($this->po)) {
            foreach ((array)$this->po as $data) {
                $res['poweroptions'] = (string)$data;
                $res['poweroptions_en'] = self::getPowerOptions($data);
                $res['poweroptions_tc'] = $view->t(self::getPowerOptions($data), Model_Translate::TC);
            }        
        }        
        return $res;
    }



    public function processRestForm()
    {
        $post = $_POST;

        //Make
        if (empty($_POST['make'])) {
            throw new Ac_Exception_MissingInformation('Car Make is empty');
        } else {
            $tmp = new MongoId($_POST['make']);
            if (strlen($_POST['make']) == 24 && $_POST['make'] == (string) $tmp) {
                $makes = self::getMakePostAd();
                if (empty($makes[$_POST['make']])) {
                    throw new Ac_Exception_MissingInformation('Car Make is empty');
                }
            } else {
                $make = self::getMake2($_POST['make']);
                /*
                if (empty($make)) {
                    throw new Ac_Exception_MissingInformation('Motorcycle Make is empty');
                } 
                 */
                if(empty($make)) {
                    $res = self::findMakeModel($_POST['make']);
                    $make  = $res['make'];
                    $model = $res['model'];
                }
            }
        }

        echo "make found: $make\n";
        echo "model found: $model\n";
        if (!empty($make)) {
            $this->make = new MongoId($make);
        }        

        //Model
        if (empty($model)) {
            $tmp = new MongoId($_POST['model']);
            if (strlen($_POST['model']) == 24 && $_POST['model'] == (string) $tmp) {
                $models = self::getModelPostAd($make);
                if (empty($models[$_POST['model']])) {
                    throw new Ac_Exception_MissingInformation('Car Model is empty');
                }
            } else {
                $models = self::findModel($_POST['model']);
                if (count($models) > 0) {
                    $model = $models[0];
                }
            }
        }

        //Nb previous user
        $nbprevious = Model_Listing_Car::getPreviousOwnersPostAd();
        if (!empty($_POST['nbprevious']) && empty($nbprevious[$_POST['nbprevious']])) {
            throw new Ac_Exception_MissingInformation('Number of previous user is empty');
        }
        if (!empty($_POST['nbprevious'])) {
            $this->numberpreviousowner = intval($_POST['nbprevious']);
        }

        //Capacity
        /*
        if (!empty($_POST['capacity']) && intval($_POST['capacity']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for capacity');
        }
        if (!empty($_POST['capacity'])) {
            $this->capacity = intval($_POST['capacity']);
        }*/


        //Color
        $colors = self::getColorPostAd();
        if (!empty($_POST['color']) && $_POST['color'] != '多彩色' &&
                empty($colors[$_POST['color']]) && array_search($_POST['color'], $colors) === false) {
            throw new Ac_Exception_MissingInformation('Color is empty');
        }
        if (!empty($colors[$_POST['color']])) {
            $this->exteriorcolor = intval($_POST['color']);
        } elseif(($res = array_search($_POST['color'], $colors)) !== false) {
            $this->exteriorcolor = intval($res);
        }

        //transmission
        $values = self::getTransmissionPostAd();
        $key    = $_POST['transmission'];
        if (!empty($key) &&
                empty($values[$key]) && array_search($key, $values) === false) {
            throw new Ac_Exception_MissingInformation('Transmission is empty');
        }
        if (!empty($values[$key])) {
            $this->transmission = intval($key);
        } elseif(($res = array_search($key, $values)) !== false) {
            $this->transmission = intval($res);
        }


        //Cartype
        $values = self::getCarTypePostAd();
        $key    = $_POST['cartype'];
        if (!empty($key) &&
                empty($values[$key]) && array_search($key, $values) === false) {
            throw new Ac_Exception_MissingInformation('Car type is empty');
        }
        if (!empty($values[$key])) {
            $this->cartype = intval($key);
        } elseif(($res = array_search($key, $values)) !== false) {
            $this->cartype = intval($res);
        }

       //Year
        if (!empty($_POST['year']) && intval($_POST['year']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for year');
        }        
        if (!empty($_POST['year'])) {
            $this->yearmanufactured = intval($_POST['year']);
        }
        //Mileage
        if (!empty($_POST['mileage']) && intval($_POST['mileage']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for mileage');
        }        
        if (!empty($_POST['mileage'])) {
            $this->mileage = intval($_POST['mileage']);
        }

        $price          = !empty($_POST['price']) ? $_POST['price'] : '';
        if (!empty($price) && $_POST['price'] != '' && !is_numeric($_POST['price']) ) {
            //echo 'price empty';exit;
            throw new Ac_Exception_MissingInformation('Price is not valid');
        }

        if ($price == 0 ){
            $this->price = 0;
        } elseif(empty($price)) {

        } else {
            $this->price = (float)$price;
        }


        parent::processRestForm();
        return true;
    }
}
